package com.oeaide.persistence;

import java.io.Serializable;
import java.util.List;


import org.hibernate.*;
import org.hibernate.cfg.*;

public class HibernateUtil {

    private static final SessionFactory sessionFactory;
    
    

    static {
        try {
            // Create the SessionFactory from hibernate.cfg.xml
            sessionFactory = new Configuration().configure("oeaide.cfg.xml").buildSessionFactory();
            //sessionFactory.openSession();
        } catch (Throwable ex) {
            // Make sure you log the exception, as it might be swallowed
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    private static SessionFactory getSessionFactory() {    	
        return sessionFactory;
    }
    

    public static boolean insertar(Serializable entity)
    {
    	Transaction trans = sessionFactory.getCurrentSession().beginTransaction();
    	try
    	{
    		sessionFactory.getCurrentSession().persist(entity);
    		trans.commit();
    		return true;
    	}
    	catch(HibernateException ex)
    	{
    		trans.rollback();
    		ex.printStackTrace();
    		return false;
    	}
    }
    
    public static Object listarTodos(Class clase)
    {
    	Transaction trans = sessionFactory.getCurrentSession().beginTransaction();
    	try
    	{
    		Criteria crit = sessionFactory.getCurrentSession().createCriteria(clase);    		
    		Object lista =  crit.list();
    		trans.commit();
    		return lista;
    	}
    	catch(HibernateException ex)
    	{
    		trans.rollback();
    		ex.printStackTrace();
    		return null;
    	}
    }
    
    public static List listarfiltrado(String query)
    {
    	Transaction trans = sessionFactory.getCurrentSession().beginTransaction();
    	try
    	{
    		List lista =  sessionFactory.getCurrentSession().find(query);
    		trans.commit();
    		return lista;
    	}
    	catch(HibernateException ex)
    	{
    		trans.rollback();
    		ex.printStackTrace();
    		return null;
    	}
    }
    
    public static Object damePorId(String classname, Serializable id)
    {
    	Transaction trans = sessionFactory.getCurrentSession().beginTransaction();
    	try
    	{
    		Object obj =  sessionFactory.getCurrentSession().get(classname, id);
    		trans.commit();
    		return obj;
    	}
    	catch(HibernateException ex)
    	{
    		trans.rollback();
    		ex.printStackTrace();
    		return null;
    	}
    }

}